import { Inject, Provide } from '@midwayjs/decorator';
import { InjectEntityModel } from '@midwayjs/typeorm';
import { AdminEntity } from 'src/entity/admin/user';
import { OrderEntity } from 'src/entity/order/orderentity';
import { StatisticEntity } from 'src/entity/Statistics/Statistics';
import { UserEntity } from 'src/entity/userinfo/user';
import {  Brackets, Repository  } from 'typeorm'
import * as md5 from 'md5'
import { PayService } from './onlypay.service';
import { Context } from 'koa';
import { BaseSysUserRoleEntity } from 'src/entity/admin/user_role';
import { BaseSysMenuEntity } from 'src/entity/admin/menu';
import { BaseSysRoleMenuEntity } from 'src/entity/admin/role_menu';
import { BaseSysRoleEntity } from 'src/entity/admin/role';
import { AdvertisementEntity } from 'src/entity/admin/advertisement';
/**
 * 描述
 */
@Provide()
export class AdminService  {
  @InjectEntityModel(OrderEntity)
  OrderModel: Repository<OrderEntity>;
  
  @InjectEntityModel(StatisticEntity)
  StatisticModel: Repository<StatisticEntity>;
  @InjectEntityModel(BaseSysUserRoleEntity)
  BaseSysUserRoleModel: Repository<BaseSysUserRoleEntity>;

  @InjectEntityModel(UserEntity)
  UserModel: Repository<UserEntity>;
  @InjectEntityModel(AdminEntity)
  AdminModel: Repository<AdminEntity>;
  @InjectEntityModel(BaseSysMenuEntity)
  BaseSysMenuModel: Repository<BaseSysMenuEntity>;
  @InjectEntityModel(BaseSysRoleMenuEntity)
  BaseSysRoleModel: Repository<BaseSysRoleMenuEntity>;

  @InjectEntityModel(AdvertisementEntity)
  AdvertisementModel: Repository<AdvertisementEntity>;
  @Inject()
  PayService:PayService
  @Inject()
  ctx: Context;
  

  /**
   * 描述
   */
  async sevrenday(num:number=7) {
     
    //  查询近七天数据 

    let order = this.OrderModel.createQueryBuilder('order')
        .select(` DATE_FORMAT(order.CreateDate,'%Y-%m-%d')`,'days')
        .addSelect(`SUM(order.actualPrice)`,'totolPrice')
        .addSelect(`count(*)`,'count')
        .where(`status =3  and  CreateDate > date_sub(curdate(), interval ${num} day) `)
        .groupBy('days')
    let view = this.StatisticModel.createQueryBuilder('StatisticModel')
                 .select(`DATE_FORMAT(CreateDate,'%Y-%m-%d')`,'days')
                 .addSelect(`StatisticModel.viewtotal`,'viewtotal')
                .where(`  CreateDate > date_sub(curdate(), interval ${num} day) `)
            let result = await    Promise.all( [ order.getRawMany() , view.getRawMany()  ])
   return  {
     code:20000,
     message:"成功",
     orderdata:result[0],
     viewdata:result[1]
   }
   

  //  return   Promise.all( [ order.getRawMany() , view.getRawMany()  ])
  //     return await this.OrderModel.
  //     createQueryBuilder('order')
  //     .select(` DATE_FORMAT(CreateDate,'%Y-%m-%d')`,'days')
  //     .addSelect(`SUM(order.actualPrice)`,'totolPrice')
  //     .addSelect(`count(*)`,'count')
  //     .where(`  CreateDate > date_sub(curdate(), interval 7 day) `)
  //     .groupBy('days')
  //     .getRawMany();

  }

  async today(){
    let todo =   [this.OrderModel.createQueryBuilder().where(` TO_DAYS(CreateDate) = TO_DAYS(NOW())`),
      this.StatisticModel.createQueryBuilder().where(` TO_DAYS(CreateDate) = TO_DAYS(NOW())`),
      this.UserModel.createQueryBuilder(),
      this.AdminModel.createQueryBuilder().where({  isagent : true })]
      let result =   await Promise.all(todo.map( v =>  v.getMany() ))
     return {
        code:20000,
        data:{
          Order: result[0],
          view:result[1][0],
          usersum:result[2].length,
          agent:result[3].length
        }
     }   
}

  async addagent(body:any){
        // this.AdminModel.createQueryBuilder()

      let result =   await this.AdminModel.findOne({ where :{ username :body.name } })
      if(result != null){
        return {
          code:40001,
          message:"用户名已存在,清重新注册"
        }

      }
        let user = new AdminEntity()
        user.isagent =true 
        user.username = body.name
        user.password = md5(  body.password).toUpperCase()
        user.phone = body.phone
        user.remark = body.remark
        let user2  = await this.AdminModel.save(user)
         let role =  new BaseSysUserRoleEntity()
         role.role=new BaseSysRoleEntity()
         role.role.id=2
         role.userId = user2

        await this.BaseSysUserRoleModel.save( role  )
          // user2.id 添加角色表
       return { 
          code:20000,
          message:"添加成功"
       }
  }

  // 查看所有代理
  async getagent(){
      let result   = await this.AdminModel.findAndCount( { where :{ isagent :true } })
      return { 
        code:20000,
        data:result
      }
  }

  //批量结算
  async  settlement(body) {

    var arr=  body.idarr.map(v => {

    return  this.OrderModel.createQueryBuilder()
      .update()
      .set({ settlementStatus:true })
      .where("id = :id", { id: v })
    });

    let result  =await Promise.all(arr.map( v => v.execute() ))
      
     
      // let result  =  await update.execute();

      return { 
         code:20000,
         message:result
      }

  }


  //  获取用户信息
  async getuserinfo(){
    //  获取用户id 
    let    user   =  await this.PayService.getuserinfo()
      // console.log( "userinfo",user);
      let id =  user.id  
    console.log("用户id",id);  
     let  role    =await this.BaseSysUserRoleModel.
     createQueryBuilder('a')
     .leftJoin('a.userId','userId')
     .leftJoinAndSelect('a.role','role')
     .where('userId.id =:id' , {  id })
     .getMany()
      // console.log(role);
      //  查询当下角色所有的菜单
      // var arr =[]
      var roles =[]
        // console.log(a);
      let find =    this.BaseSysMenuModel
        .createQueryBuilder('menu')
        .select([ 'menu.id','menu.icon','menu.isShow','menu.keepAlive','menu.name','menu.orderNum','menu.parentId','menu.perms','menu.router','menu.type',
        'menu.viewPath'])
        .leftJoin("menu.roles", "roles")
        // .orWhere('roles.roleId = :id',{ id:1 } )
        // .orWhere('roles.roleId = :id',{ id:2 } )
        find.andWhere(new Brackets( (qb)=>{
          role.forEach( v=>{
            // console.log("多角色查询",v.role.id);
            qb.orWhere(`roles.roleId = ${v.role.id}` )
            roles.push({ label:v.role.label ,name:v.role.name  })      
            // qb.orWhere(`roles.roleId = v.role.id` )
          })
        }))
      // role.map(async ( v) =>{
      //   roles.push({ label:v.role.label ,name:v.role.name  })      
      // })
      let a =await find.getMany()
      return { 
         code:20000,
         data:{
          roles:roles,
          permissionList:a
         }
      }

  }

  async extension(body){
     return  {  
        code:20000,
        data:await this.AdvertisementModel.save(body)
     }  
  }
  

}